'use strict';

exports.__esModule = true;

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

exports.default = loadingMiddleware;

var _loading = require('../components/loading');

var _loading2 = _interopRequireDefault(_loading);

var _api = require('../libs/api');

var _api2 = _interopRequireDefault(_api);

require('../libs/promise.finally');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function loadingMiddleware(_ref) {
  var dispatch = _ref.dispatch,
      getState = _ref.getState;

  return function (next) {
    return function (action) {
      var promise = action.promise,
          _action$meta = action.meta,
          meta = _action$meta === undefined ? { suppressLoading: false } : _action$meta;


      if (!promise) {
        return next(action);
      }

      if (!meta.suppressLoading) {
        _loading2.default.show();
      }

      var actionPromise = promise(dispatch, getState, _api2.default);

      function finallyHandler() {
        if (!meta.suppressLoading) {
          _loading2.default.hide();
        }
      }

      actionPromise.finally(finallyHandler);

      return next((0, _extends3.default)({}, action, { promise: actionPromise }));
    };
  };
}